package com.gollum.aspect;

import com.gollum.common.annotation.FlowLimiter;
import com.gollum.common.constant.SystemConstants;
import com.gollum.common.enums.LimitType;
import com.gollum.common.exception.ServiceException;
import com.gollum.common.utils.MessageUtils;
import com.gollum.common.utils.ServletUtils;
import com.gollum.common.utils.StringUtils;
import com.gollum.common.utils.ip.IpUtils;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;

/**
 * 限流切面
 *
 * @author Herther
 * @createTime 2022年11月17日 23:00:00
 * @since 1.0.0
 */
@Aspect
@Component
@Slf4j
public class FlowLimiterAspect {


    private RedisTemplate<Object, Object> redisTemplate;

    private RedisScript<Long> limitScript;

    @Autowired
    public void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setLimitScript(RedisScript<Long> limitScript) {
        this.limitScript = limitScript;
    }

    @Before("@annotation(flowLimiter)")
    public void doBefore(JoinPoint point, FlowLimiter flowLimiter) throws Throwable {
        String key = flowLimiter.key();
        int time = flowLimiter.time();
        int count = flowLimiter.count();

        String combineKey = getCombineKey(flowLimiter, point);
        List<Object> keys = Collections.singletonList(combineKey);
        try {
            Long number = redisTemplate.execute(limitScript, keys, count, time);
            if (StringUtils.isNull(number) || number.intValue() > count) {
                throw new ServiceException(MessageUtils.getMsg("request.flow.limit.fail"));
            }
            log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), key);
        }
        catch (ServiceException e) {
            throw e;
        }
        catch (Exception e) {
            throw new RuntimeException("服务器限流异常，请稍候再试");
        }
    }

    public String getCombineKey(FlowLimiter flowLimiter, JoinPoint point) {
        StringBuffer stringBuffer = new StringBuffer(flowLimiter.key());
        if (flowLimiter.limitType() == LimitType.IP) {
            stringBuffer.append(IpUtils.getIpAddr(ServletUtils.getRequest())).append(SystemConstants.SPLIT);
        }
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class<?> targetClass = method.getDeclaringClass();
        stringBuffer.append(targetClass.getName()).append(SystemConstants.SPLIT).append(method.getName());
        return stringBuffer.toString();
    }
}
